﻿using System;
using EP.Base.BaseService.Manager.Config.Enum;
using EP.Base.BaseService.Manager.Interface;
using EP.Base.BaseService.Manager.Interface.Business;
using EP.Base.BaseService.Manager.Interface.Common;
using EP.Base.BaseService.Manager.Interface.Data;
using EP.Base.BaseService.Manager.Model.Entity;

namespace EP.Base.BaseService.Manager.Business.Task
{
    /// <summary>
    /// 删除es索引服务
    /// </summary>
    public class DeleteIndexTask : IEsIndexHandelTask
    {
        private readonly IEsClusters _esClusters;
        private readonly IIndexConfigs _indexConfigs;
        private readonly IIndexDeleteLogs _indexDeleteLogs;
        private readonly IEsData _esData;
        private readonly IServiceSimplifyLog _serviceSimplifyLog;
        public DeleteIndexTask(IEsClusters esClusters, IIndexConfigs indexConfigs, IIndexDeleteLogs indexDeleteLogs, IEsData esData, IServiceSimplifyLog serviceSimplifyLog)
        {
            _esClusters = esClusters;
            _indexConfigs = indexConfigs;
            _indexDeleteLogs = indexDeleteLogs;
            _esData = esData;
            _serviceSimplifyLog = serviceSimplifyLog;
        }

        public bool Exec(EsTaskConfig taskConfig)
        {
            var indexConfig = _indexConfigs.Get(taskConfig.IndexConfigId);
            if (indexConfig == null)
                return true;
            var esClusterInfo = _esClusters.Get(indexConfig.ClusterId);
            if (esClusterInfo == null)
                return true;

            var needDeleteIndexs = _indexDeleteLogs.GetByIndexConfigId(taskConfig.IndexConfigId,(short) EnumIndexDeleteLogState.NeedDelete);

            foreach (var indexDeleteLog in needDeleteIndexs)
            {
                IndexDeleteLog log = indexDeleteLog;
                _serviceSimplifyLog.ExecSl("删除索引;indexDeleteLogId=" + log.Id + ";IndexName=" + log.IndexName,
                    () =>
                    {
                        var result = _esData.DeleteIndex(esClusterInfo.ServiceHostArr, log.IndexName);
                        if (result)
                        {
                            _indexDeleteLogs.UpdateStateAndDeleteTimeById(log.Id,(short)EnumIndexDeleteLogState.Deleted, DateTime.Now);
                        }
                    });
            }
            return true;
        }
    }
}
